import { login, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  roles: [],
  permissions: [],
  menuPermissions: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
  SET_MENU_PERMISSIONS: (state, menuPermissions) => {
    state.menuPermissions = menuPermissions
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password })
        .then(response => {
          const { data } = response
          commit('SET_TOKEN', data.token)
          commit('SET_NAME', data.user.name)
          commit('SET_AVATAR', data.user.avatar)
          commit('SET_ROLES', data.roles)
          commit('SET_PERMISSIONS', data.permissions)
          commit('SET_MENU_PERMISSIONS', data.menuPermissions)
          
          setToken(data.token)
          // 将菜单权限存储到localStorage
          localStorage.setItem('menu_permissions', JSON.stringify(data.menuPermissions))
          
          resolve(data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 用户登出
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout(state.token)
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_PERMISSIONS', [])
          commit('SET_MENU_PERMISSIONS', [])
          removeToken()
          resetRouter()
          localStorage.removeItem('menu_permissions')
          
          // 重置访问的视图
          dispatch('tagsView/delAllViews', null, { root: true })
          
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 重置令牌
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_PERMISSIONS', [])
      commit('SET_MENU_PERMISSIONS', [])
      removeToken()
      localStorage.removeItem('menu_permissions')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
} 